package cadc.daos;



import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cadc.models.Entrant;

public class EntrantDao extends JdbcDaoSupport {

	public boolean deleteEntrantById(int id) {
		if(super.getJdbcTemplate().update("delete from entrants where id="+id)>0)return true;
		return false;
	}

	public Entrant getEntrantById(int id) {
		String sql = "select * from entrants where id="+id;
		return (Entrant)super.getJdbcTemplate().queryForObject(sql, new EntrantRowMapper());
	}

	public int saveEntrant(Entrant en) {
		String sql = "insert into entrants (id, name, gender, number, phone, email, college) values (null, ?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, en.getName(), en.getGender(), en.getNumber(), en.getPhone(), en.getEmail(), en.getCollege())>0){
			return super.getJdbcTemplate().queryForInt("select max(id) from entrants");
		}else return 0;
	}

	public boolean updateEntrant(Entrant en) {
		String sql="update entrants set name=?, gender=?, number=?, phone=?, email=?, college=? where id=?";
		if(super.getJdbcTemplate().update(sql, en.getName(),en.getGender(),en.getNumber(),en.getPhone(),en.getEmail(),en.getCollege(),en.getId())>0){
			return true;
		}else return false;
	}

	class EntrantRowMapper implements RowMapper<Object>{
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			Entrant en = new Entrant();
			en.setId(rs.getInt("id"));
			en.setName(rs.getString("name"));
			en.setGender(rs.getString("gender"));
			en.setNumber(rs.getString("number"));
			en.setPhone(rs.getString("phone"));
			en.setEmail(rs.getString("email"));
			en.setCollege(rs.getString("college"));
			return en;
		}	
	}
}
